import React, { useState, useEffect, useRef, useContext } from 'react';
import './App.css';

// 创建召唤兽状态上下文
const BbListContext = React.createContext();

// 初始召唤兽数据
const initialBbList = [
  {
    id: 1,
    name: '泡泡',
    des: '泡泡',
    img: 'bubble.png',
    jnList: []
  },
  {
    id: 2,
    name: '飞鱼',
    des: '飞鱼',
    img: 'flying-fish.png',
    jnList: []
  },
  {
    id: 3,
    name: '龙虾',
    des: '龙虾',
    img: 'lobster.png',
    jnList: []
  }
];

// 召唤兽状态提供者
function BbListProvider({ children }) {
  const [items, setItems] = useState(initialBbList);
  const [index, setIndex] = useState(0);
  const [currentBb, setCurrentBb] = useState(null);

  useEffect(() => {
    if (items.length > 0) {
      setCurrentBb(items[index]);
    }
  }, [index, items]);

  const save = (data) => {
    const updatedItems = [...items];
    updatedItems[index] = {
      ...updatedItems[index],
      jnList: data.jnList
    };
    setItems(updatedItems);
    alert('保存成功！');
  };

  const add = (data) => {
    const newBb = {
      id: items.length + 1,
      name: `召唤兽${items.length + 1}`,
      des: `召唤兽${items.length + 1}`,
      img: `summon-${items.length + 1}.png`,
      jnList: data.jnList
    };
    setItems([...items, newBb]);
    setIndex(items.length);
  };

  const clear = () => {
    const updatedItems = [...items];
    updatedItems[index] = {
      ...updatedItems[index],
      jnList: []
    };
    setItems(updatedItems);
  };

  return (
    <BbListContext.Provider value={{ 
      items, 
      index, 
      currentBb, 
      setIndex, 
      save, 
      add, 
      clear 
    }}>
      {children}
    </BbListContext.Provider>
  );
}

// 使用召唤兽状态的钩子
function useBbList() {
  return useContext(BbListContext);
}

// 音频常量
const JN_SOURCE_LISTS = [
  { id: 1, des: '连击', img: 'skill1.jpg' },
  { id: 2, des: '必杀', img: 'skill2.jpg' },
  { id: 3, des: '偷袭', img: 'skill3.jpg' },
  { id: 4, des: '吸血', img: 'skill4.jpg' },
  { id: 5, des: '夜战', img: 'skill5.jpg' },
  { id: 6, des: '强力', img: 'skill6.jpg' },
  { id: 7, des: '感知', img: 'skill7.jpg' },
  { id: 8, des: '驱鬼', img: 'skill8.jpg' },
  { id: 9, des: '隐身', img: 'skill9.jpg' },
  { id: 10, des: '神佑', img: 'skill10.jpg' },
];

// 工具函数
const getRandomItem = (array) => {
  return array[Math.floor(Math.random() * array.length)];
};

const getDifferArrayRandomItem = (sourceArray, targetArray) => {
  const diffArray = sourceArray.filter(item => 
    !targetArray.some(t => t.des === item.des)
  );
  return getRandomItem(diffArray);
};

const getRandomFixedLengthArray = (array, length) => {
  const shuffled = [...array].sort(() => 0.5 - Math.random());
  return shuffled.slice(0, length);
};

// 对话框基础组件
function DialogBase({ title, onCloseClick, children }) {
  return (
    <div className="dialog-overlay">
      <div className="dialog">
        <div className="dialog-header">
          <div className="dialog-header-title">{title}</div>
          <div className="dialog-header-close" onClick={onCloseClick}>
            ×
          </div>
        </div>
        <div className="dialog-content">
          {children}
        </div>
      </div>
    </div>
  );
}

// 召唤兽打书组件
function DialogBooks() {
  const { items, index, currentBb, setIndex, save, add, clear } = useBbList();
  const [bbAttsMap, setBbAttsMap] = useState({
    gongji: '',
    fali: '',
    fangyu: '',
    sudu: '',
    tili: '',
    duoshan: '',
    shouming: '',
    chengzhang: '',
    wuxing: '',
  });
  
  const [currentSelect, setCurrentSelect] = useState({
    des: '',
    img: '',
    name: '',
  });
  
  const [jnLengthRef, setJnLengthRef] = useState(0);
  const [learnIndexRef, setLearnIndexRef] = useState(0);
  const [learningRef, setLearningRef] = useState(false);
  const [showRenzheng, setShowRenzheng] = useState(false);
  const [bgMusicFlag, setBgMusicFlag] = useState(false);
  const [jnLists, setJnLists] = useState([]);
  
  const bagJnLists = JN_SOURCE_LISTS;
  const audioRef = useRef(null);
  const bgAudioRef = useRef(null);

  // 初始化技能
  const getRandomAttrs = () => {
    setBbAttsMap({
      gongji: 1000 + Math.floor(Math.random() * 700),
      fali: 1000 + Math.floor(Math.random() * 2000),
      fangyu: 1000 + Math.floor(Math.random() * 1000),
      sudu: 1000 + Math.floor(Math.random() * 700),
      tili: 1000 + Math.floor(Math.random() * 4000),
      duoshan: 1000 + Math.floor(Math.random() * 700),
      shouming: 1000 + Math.floor(Math.random() * 7000),
      chengzhang: (1 + parseFloat(Math.random().toFixed(2) * 0.3)).toFixed(2),
      wuxing: getRandomItem(['金', '木', '水', '火', '土']),
    });
    
    const jnLenth = 3 + Math.floor(Math.random() * 8);
    setJnLengthRef(jnLenth);
    
    const jnInitArrs = getRandomFixedLengthArray(JN_SOURCE_LISTS, jnLenth);
    const newJnLists = jnInitArrs.map((e, idx) => ({
      ...e,
      animated: false
    }));
    
    setJnLists(newJnLists);
    setShowRenzheng(newJnLists.some(e => 
      ['diyuliehuo', 'shuimanjinshan', 'taishanyading', 'benleizhou'].includes(e?.name)
    ));
  };

  // 控制认证按钮显示
  useEffect(() => {
    setShowRenzheng(jnLists.some(e => 
      ['diyuliehuo', 'shuimanjinshan', 'taishanyading', 'benleizhou'].includes(e?.name)
    ));
  }, [jnLists]);

  // 监听当前召唤兽变化
  useEffect(() => {
    if (currentBb?.jnList?.length > 0) {
      setJnLists(currentBb.jnList);
      const jnLenth = currentBb.jnList.filter(e => e?.des).length;
      setJnLengthRef(jnLenth);
      setShowRenzheng(currentBb.jnList.some(e => 
        ['diyuliehuo', 'shuimanjinshan', 'taishanyading', 'benleizhou'].includes(e?.name)
      ));
    } else {
      getRandomAttrs();
    }
  }, [currentBb]);

  // 播放音效
  const playAudio = () => {
    if (audioRef.current) {
      audioRef.current.currentTime = 0;
      audioRef.current.play()
        .then(() => {
          setTimeout(() => {
            if (audioRef.current) {
              audioRef.current.pause();
            }
          }, 1000);
        })
        .catch(error => {
          console.error('播放失败:', error);
        });
    }
  };

  // 选择召唤兽
  const selectBbEvent = () => {
    setIndex(prev => (prev >= items.length - 1 ? 0 : prev + 1));
  };

  // 背包物品选择
  const bagSelectEvent = (it) => {
    setCurrentSelect({
      des: it.des,
      img: it.img,
      name: it.des
    });
  };

  // 学习技能
  const learnEvent = () => {
    if (!currentSelect.des) {
      alert('请先选择要学习的技能书！');
      return;
    }
    
    const exists = jnLists.some(e => e?.des === currentSelect.des);
    if (exists) {
      alert(`${currentSelect.des}技能已重复！`);
      return;
    }
    
    playAudio();
    
    // 找到第一个空技能格或随机替换一个已有技能
    let targetIndex = Math.floor(Math.random() * jnLengthRef);
    
    // 创建新技能对象
    const newSkill = {
      ...currentSelect,
      animated: true,
    };
    
    // 更新技能列表
    const newJnLists = [...jnLists];
    newJnLists.splice(targetIndex, 1, newSkill);
    
    setJnLists(newJnLists);
    setCurrentSelect({
      des: '',
      img: '',
      name: '',
    });
    
    setLearnIndexRef(targetIndex);
    setLearningRef(true);
    setTimeout(() => setLearningRef(false), 1000);
    
    setShowRenzheng(newJnLists.some(e => 
      ['diyuliehuo', 'shuimanjinshan', 'taishanyading', 'benleizhou'].includes(e?.name)
    ));
  };

  // 重置技能
  const resetEvent = () => {
    getRandomAttrs();
  };

  // 认证技能
  const renzhengEvent = () => {
    const newJnLists = [...jnLists];
    newJnLists.forEach((e, i) => {
      if (['diyuliehuo', 'shuimanjinshan', 'taishanyading', 'benleizhou'].includes(e?.name)) {
        const newItem = getDifferArrayRandomItem(JN_SOURCE_LISTS, newJnLists);
        newJnLists.splice(i, 1, newItem);
      }
    });
    
    setJnLists(newJnLists);
  };

  // 保存
  const saveEvent = () => {
    save({
      jnList: jnLists,
    });
  };

  // 添加新召唤兽
  const addEvent = () => {
    getRandomAttrs();
    add({
      jnList: jnLists,
    });
    setIndex(items.length);
  };

  // 清除
  const clearEvent = () => {
    if (window.confirm('确定要清除当前召唤兽的所有技能吗？')) {
      clear();
      setShowRenzheng(false);
    }
  };

  // 背景音乐控制
  const musicEvent = () => {
    if (bgAudioRef.current) {
      if (bgMusicFlag) {
        bgAudioRef.current.pause();
      } else {
        bgAudioRef.current.play();
      }
      setBgMusicFlag(!bgMusicFlag);
    }
  };

  return (
    <DialogBase 
      title="梦幻打书我最行" 
      onCloseClick={() => {}}
    >
      <div className="dobooks-container">
        <audio id="myAudio" ref={audioRef} src="/click2.mp3" />
        <audio id="CA" ref={bgAudioRef} src="/CA.mp3" />
        
        <div className="dobooks-left">
          <div className="dobooks-left-img">
            <img src={`/assets/BB/${currentBb?.img || 'furong.png'}`} alt={currentBb?.name} />
          </div>
          
          <div className="dobooks-left-info">
            <div className="dobooks-left-info-txt">{currentBb?.des}</div>
            <div 
              className="dobooks-left-info-btn" 
              onClick={selectBbEvent} 
              style={{ display: items.length > 1 ? 'block' : 'none' }}
            >
              切换
            </div>
          </div>
          
          <div className="dobooks-left-attrs">
            {Object.entries(bbAttsMap).map(([key, value]) => (
              <div 
                key={key} 
                className="dobooks-left-attrs-lib"
                style={{ color: key.includes('hot') ? '#c19139' : '#f8f8f8' }}
              >
                {key === 'gongji' && '攻击资质：'} 
                {key === 'fali' && '法力资质：'} 
                {key === 'fangyu' && '防御资质：'} 
                {key === 'sudu' && '速度资质：'} 
                {key === 'tili' && '体力资质：'} 
                {key === 'duoshan' && '躲闪资质：'} 
                {key === 'shouming' && '寿 命：'} 
                {key === 'chengzhang' && '成 长：'} 
                {key === 'wuxing' && '五 行：'}
                {value}
              </div>
            ))}
          </div>
          
          <div className="dobooks-left-jn">
            {jnLists.map((it, index) => (
              <div 
                key={index} 
                className={`dobooks-left-jn-lib ${learningRef && index === learnIndexRef ? 'learning' : ''}`}
              >
                {it?.img && <img src={it.img} alt={it.des} />}
              </div>
            ))}
            
            <div className="dobooks-left-jn-btn" onClick={resetEvent}>
              重置
            </div>
            
            {showRenzheng && (
              <div className="dobooks-left-jn-btn" onClick={renzhengEvent}>
                认证
              </div>
            )}
            
            <div className="dobooks-left-jn-btn" onClick={saveEvent}>
              保存
            </div>
            
            <div className="dobooks-left-jn-btn _hot add" onClick={addEvent}>
              添加
            </div>
            
            <div className="dobooks-left-jn-btn _hot clear" onClick={clearEvent}>
              清除
            </div>
            
            <div className="dobooks-left-jn-btn _hot audio" onClick={musicEvent}>
              {bgMusicFlag ? '暂停' : '播放'}
            </div>
          </div>
        </div>
        
        <div className="dobooks-right">
          <div className="dobooks-right-learn">
            <div className="dobooks-right-learn-shoujue">
              {currentSelect?.img ? (
                <img src={currentSelect.img} alt={currentSelect.name} />
              ) : (
                <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#b4bbe0' }}>
                  未选择
                </div>
              )}
            </div>
            
            <div className="dobooks-right-learn-btn">
              <div className="dobooks-right-learn-btn-txt">
                请放入魔兽要诀或者高级魔兽要诀
              </div>
              <div className="dobooks-right-learn-btn-b" onClick={learnEvent}>
                学习
              </div>
            </div>
          </div>
          
          <div className="dobooks-right-bags">
            {bagJnLists.map((it, idx) => (
              <div
                key={`bag_${idx}`}
                className="dobooks-right-bags-lib"
                onClick={() => bagSelectEvent(it)}
              >
                <img src={`/assets/skills/${it.img}`} alt={it.des} />
                <div className="dobooks-right-bags-lib-des">{it.des}</div>
              </div>
            ))}
          </div>
          
          <div className="dobooks-right-des">
            说明 <br />
            随兽要诀能赋予召唤兽某种技能，但是每次使用的同時会消除该召唤兽的一项原有技能，技能数量≤2的召唤兽有一定几率不会有技能。
          </div>
        </div>
      </div>
    </DialogBase>
  );
}

// 主应用组件
function App() {
  return (
    <div className="app">
      <h1>梦幻西游召唤兽打书模拟器</h1>
      <p>在React 18中实现的召唤兽技能学习系统</p>
      
      <div className="game-container">
        <DialogBooks />
      </div>
      
      <div className="instructions">
        <h2>使用说明：</h2>
        <ol>
          <li>在左侧查看召唤兽属性和已有技能</li>
          <li>从底部背包中选择技能书</li>
          <li>点击"学习"按钮将技能打入召唤兽</li>
          <li>使用"重置"清空所有技能</li>
          <li>"认证"按钮可修复特殊技能</li>
          <li>点击右上角×关闭对话框</li>
        </ol>
      </div>
    </div>
  );
}

export default App;